<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="signature-canvas" width="800" height="600" style="border: 1px solid black;margin: 0 auto;"></canvas>
  <script>
    const canvas = document.getElementById("signature-canvas");
    const ctx = canvas.getContext("2d");

    let isDrawing = false; // 是否正在画线
    let lastX = 0; // 上一个点的 X 坐标
    let lastY = 0; // 上一个点的 Y 坐标
    canvas.addEventListener("mousedown", (e) => {
      isDrawing = true;
      [lastX, lastY] = [e.offsetX, e.offsetY];
    });
    // 监听 canvas 元素的鼠标事件，实现手写签名功能
    canvas.addEventListener("mousemove", (e) => {
      if (isDrawing) {
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        [lastX, lastY] = [e.offsetX, e.offsetY];
      }
    });

    canvas.addEventListener("mouseup", () => {
      isDrawing = false;
    });

    canvas.addEventListener("mouseout", () => {
      isDrawing = false;
    });
    // 清空签名
    function clearCanvas() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
    // 导出签名
    function saveSignature() {
      const dataURL = canvas.toDataURL();
      console.log(dataURL);
    }

  </script>
</body>

</html>